<template>
  <div class="app-container">
    <el-form ref="newsForm" :rules="rules" :model="newsForm" label-width="120px">
      <el-form-item label="文章标题:" prop="title">
        <el-input v-model.trim="newsForm.title" />
      </el-form-item>
      <el-form-item label="文章封面:" prop="cover">
        <el-upload
          class="cover-uploader"
          :show-file-list="false"
          :http-request="addCover"
          :before-upload="beforeUpload"
          action="action"
        >
          <img v-if="newsForm.cover" :src="newsForm.cover" class="cover">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容:" prop="content">
        <div style="border: 1px solid #ccc; margin-top: 10px">
          <!-- 工具栏 -->
          <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :default-config="toolbarConfig" />
          <!-- 编辑器 -->
          <Editor
            v-model="newsForm.content"
            style="height: 400px; overflow-y: hidden"
            :default-config="editorConfig"
            @onCreated="onCreated"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('newsForm')">提交</el-button>
        <el-button @click="onCancel">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { addNews, uploadCover, getOneNews, updateOneNews } from '@/api/news'
export default {
  name: 'NewsEditor',
  components: { Editor, Toolbar },
  props: {
    type: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      editor: null,
      toolbarConfig: {
        // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
        // excludeKeys: [ /* 隐藏哪些菜单 */ ],
      },
      formData: null,
      loading: false,
      newsForm: {
        title: '',
        cover: '',
        content: ''
      },
      cachesId: '',
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            // 后端上传地址，必填
            server: 'http://127.0.0.1:3005/upload/news',
            customInsert(res, insertFn) {
              //  {"code":20000,"data":{"message":"添加新闻图片成功","imgUrl":"http://127.0.0.1:3005/news/avatar_1678197437113.png"}}
              // 从 res 中找到 url alt href ，然后插入图片
              const url = res.data.imgUrl
              insertFn(url)
            },
            fieldName: 'files',
            // 1M，单个文件的最大体积限制，默认为 2M
            maxFileSize: 1 * 1024 * 1024,
            // 最多可上传几个文件，默认为 100
            maxNumberOfFiles: 1,
            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
            allowedFileTypes: ['image/*'],
            // 15 秒，超时时间，默认为 10 秒
            timeout: 15 * 1000,
            headers: {
              Accept: 'text/x-json',
              Authorization: `Bearer ${getToken()}`
            }
          }
        }
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        cover: [{ required: true, message: '请选择封面', trigger: 'blur' }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      }
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },

  watch: {
    id: {
      immediate: true,
      deep: true,
      handler(newValue) {
        this.type === 'edit' &&
          !!newValue &&
          newValue !== this.cachesId &&
          (this.cachesId = newValue) &&
          this.getEditInfo(newValue)
      }
    }
  },
  mounted() {
    console.log('aaaa')
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁 editor ，重要！！！
  },
  methods: {
    // 拉编辑数据
    async getEditInfo(id) {
      try {
        var {
          data: { title, cover, content }
        } = await getOneNews(id)
        this.newsForm = { title, cover, content }
      } catch (error) {
        console.log('error: ', error)
      }
    },
    // 上传封面
    async addCover() {
      const formData = this.formData
      try {
        var result = await uploadCover(formData)
        this.newsForm.cover = result.data.imgUrl
        this.$message({
          type: 'success',
          message: '封面添加成功'
        })
      } catch (error) {
        console.log('error: ', error)
      }
    },
    // 上传文件之前钩子
    beforeUpload(file) {
      const type = file.name.substring(file.name.lastIndexOf('.') + 1)
      const typeInfo = ['jpg', 'png', 'jpeg']
      if (!typeInfo.includes(type)) {
        this.$message({
          type: 'error',
          message: '只支持jpg,png,jpeg文件格式！'
        })
        return false
      }
      if (file.size / 1024 > 500) {
        this.$message({ type: 'error', message: '图片不能大于500kb！' })
        return false
      }
      const formData = new FormData()
      formData.append('files', file)
      this.formData = formData
    },
    // 提交
    onSubmit(formName) {
      this.$refs[formName].validate(async(valid) => {
        const newsForm = this.newsForm
        if (valid) {
          try {
            const response = this.id ? await updateOneNews(this.id, newsForm) : await addNews(newsForm)
            console.log('response: ', response)
            this.loading = false
            this.$message({
              type: 'success',
              message: this.id ? '新闻修改成功' : '新闻添加成功'
            })
            this.$store.dispatch('tagsView/delView', this.$route).then(() => {
              // this.newsForm = {
              //   title: '',
              //   cover: '',
              //   content: ''
              // }
              // this.$route.meta.isFlushed = true
              this.cachesId = ''
              console.log('this.cachesId222: ', this.cachesId)
              this.$router.replace('/news/index')
            })
          } catch (error) {
            console.log('error: ', error)
            this.loading = false
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 返回
    onCancel() {
      this.$store.dispatch('tagsView/delView', this.$route).then(() => {
        this.newsForm = {
          title: '',
          cover: '',
          content: ''
        }
        this.$router.replace('/news/index')
      })
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错
    }
  }
}
</script>
<style lang="scss" scoped></style>
